import React from 'react'
import {  Form, Button, Input, message} from 'antd'
import { doLogin } from '@a/user'
import { useDispatch } from 'react-redux'
import { initUser, filterAuth } from '@s/modules/user'
import { useNavigate } from 'react-router-dom'
export default function Login() {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const userLogin = (params) => {
    doLogin(params).then(res => {
      console.log(res);
      if(res.data.code === 200) {
        const { role, userInfo, token } = res.data.data;
        // 缓存起来 做redux持久化
        localStorage.setItem('role', role);
        localStorage.setItem('userInfo', JSON.stringify(userInfo));
        localStorage.setItem('token', token);
        // 存储到redux中
        dispatch(initUser(res.data.data))
        // 过滤当前角色侧边导航数据和路由数据
        dispatch(filterAuth())
        message.success(res.data.msg, 2, ()=> {
          navigate('/dashBoard', {replace: true})
        })
      }
    })
  }
  return (
    <div>
      <Form
        onFinish={
          userLogin
        }
      >
        <Form.Item
          label="用户名"
          name="userName"
          rules={[
            {
              required: true,
              message: '用户名必填'
            },
            {
              pattern: /^\w{4,8}$/,
              message: '用户名是4到8位英文数字字母下划线组成'
            }
          ]}
        >
          <Input/>
        </Form.Item>
        <Form.Item
          label="密码"
          name="pwd"
          rules={[
            {
              required: true,
              message: '密码必填'
            },
            {
              pattern: /^\w{4,8}$/,
              message: '用户名是4到8位英文数字字母下划线组成'
            }
          ]}
        >
          <Input type='password'/>
        </Form.Item>
        <Form.Item
          
        >
          <Button htmlType='submit'>登录</Button>
          <Button htmlType='reset'>重置</Button>
        </Form.Item>
      </Form>
    </div>
  )
}
